package dilmaj.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;

import dilmaj.shared.StarEntryVO;
import dilmaj.shared.StarPrivilegeVO;

public class RankButton extends Button implements ClickHandler {
	int coef;
	StarEntryVO dataVO;
	StarPanel owner;
	private StarServiceAsync starSvc = GWT.create(StarService.class);
	
	public RankButton(StarPanel owner, int coef) {
		this.owner=owner;
		
		this.coef=coef;
		this.dataVO=owner.getDataVO();
		
		String title="";
		if (coef>0)
			title="+";
		title=title.concat(coef+"");
		setText(title);
		
		addClickHandler(this);
	}
	
	AsyncCallback<StarEntryVO> entryCallback=new AsyncCallback<StarEntryVO>() {

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(StarEntryVO result) {
			// TODO Auto-generated method stub
			//DataStore.installDataStore();
			DataStore.hideWait();
		}
		
	};
	
	AsyncCallback<StarEntryVO> suggestionCallback=new AsyncCallback<StarEntryVO>() {

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(StarEntryVO result) {
			// TODO Auto-generated method stub
			owner.getDataVO().addAttachment(result);
			if (starSvc == null) {
			      starSvc = GWT.create(StarService.class);
			    }
			/*StarSuggestionVO suggestionVO=owner.getSuggestionVO();
			suggestionVO.setCaption(owner.getSuggestionText());*/
			//owner.getDataVO().setCaption(owner.getDataCaption());
			DataStore.add(result);
			owner.addPrivilege(DataStore.getUsername());
			DataStore.hideWait();
			//starSvc.updateEntry(owner.getDataVO(), entryCallback);
		}
	};

	@Override
	public void onClick(ClickEvent event) {
		dataVO.setRank(dataVO.getRank()+coef);
		owner.setRank(dataVO.getRank());
		if (DataStore.getUserid()!=-1) {
			if (!dataVO.isPrivilegedBy(DataStore.getUsername())) {
				if (starSvc == null) {
				      starSvc = GWT.create(StarService.class);
				    }
				StarPrivilegeVO privilege=new StarPrivilegeVO();
				privilege.setCaption("*");
				privilege.setUserID(DataStore.getUserid());
				privilege.setUserName(DataStore.getUsername());
				DataStore.showWait();
				starSvc.addEntry(privilege, suggestionCallback);
			}
		} else {
			DataStore.showWait();
			starSvc.updateEntry(owner.getDataVO(), entryCallback);
		}
	}
}
